import { ActionType } from "../../index";
import { fromJS } from "immutable";
import { v4 as uuidv4 } from "uuid";

const config = {
  instances: {
    default: {
      data: undefined,
      title: undefined,
      componentId: undefined,
    },
  },
};
const initState = fromJS(config);

function reduxReducers(state = initState, action: any) {
  let newState = state;
  switch (action.type) {
    case ActionType.OBJECT_LIST_INIT:
      newState = state.withMutations((item: any) => {
        item.setIn(["instances", action.componentId, "data"], action.data);
      });
      return newState;
    case ActionType.OBJECT_LIST_UPDATE:
      let newData: any[] = [];
      newData = state
        .getIn(["instances", action.componentId, "data"])
        .concat(newData);
      newData.push({ ...action.data, uuid: uuidv4() });
      newState = state.withMutations((item: any) => {
        item.setIn(["instances", action.componentId, "data"], newData);
      });
      return newState;
    default:
      break;
  }
  return state;
}

export default reduxReducers;
